﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ChoViet.Model;
using ChoViet.Lib.Common;
using System.Linq.Dynamic;
using ChoViet.Lib.Paging;
using ChoViet.Cms.ViewModels;
using ChoViet.Lib.Helpers;
using ChoViet.CMS.Properties;
using System.Text.RegularExpressions;
namespace ChoViet.CMS.Controllers
{
	[RoleHelper(Roles = RoleSystem.Dictionary)]
    public class MenuController : BaseController
    {
        //
        // GET: /Menu/
        ChoVietDataContext eDataContext = new ChoVietDataContext();
        public ActionResult Index()
        {
            try
            {
                    string order = UserState.getUserStateFromRequest("menu.order", "order", "ID").ToString();
                    string orderDir = UserState.getUserStateFromRequest("menu.orderDir", "orderDir", "desc").ToString();

                    string keyword = UserState.getUserStateFromRequest("menu.Keyword", "Keyword", "").ToString();
                    var typeid = Utils.ParseInt(UserState.getUserStateFromRequest("menu.Type", "ddlMenuType", 0));

                    var pageNumber = Convert.ToInt32(UserState.getUserStateFromRequest("menu.PageNumber", "page", 1));
                    var pageIndex = pageNumber - 1;
                    var pageSize = Convert.ToInt32(UserState.getUserStateFromRequest("menu.PageSize", "pageSize", 20));

                    var menus = eDataContext.Menus
                        .Where(a => typeid > 0 ? a.TypeID == typeid : true)                        
                        .Where(a => string.IsNullOrEmpty(keyword) ? true :
                            a.Name.ToLower().Contains(keyword.ToLower().Trim()))
                        .OrderBy(string.Format("{0} {1}", order, orderDir))
                        .ToPagedList(pageIndex, pageSize);

                    ViewData["orderDir"] = orderDir;
                    ViewData["order"] = order;
                    MenuViewIndexModel m = new MenuViewIndexModel();
                    m.Menus = menus;
                    m.MenuTypes = eDataContext.MenuTypes.ToList();
                    m.FilterName = keyword;
					m.CurrentMenuType = typeid;
                    return View(m);
            }
            catch (Exception exp)
            {
                return View();
            }
        }

        //
        // GET: /Menu/Details/5
        public ActionResult Details(int id)
        {
            try
            {
                    var item = eDataContext.Menus.SingleOrDefault(e => e.ID == id);
                    return View(item);
            }
            catch (Exception exp)
            {
                return View();
            }
        }

        //
        // GET: /Menu/Create
        public ActionResult Create()
        {
            try
            {
                MenuViewEditModel model = new MenuViewEditModel();
                model.MenuTypes = eDataContext.MenuTypes.ToList();
                model.Menus = eDataContext.Menus.Where(e => e.ParentID == null).ToList();
                model.ArticleCategories = eDataContext.ArticleCategories.Where(e => e.ActiveYN == true).ToList();
                    return View(model);
            }
            catch (Exception exp)
            {
                Messages.AddErrorFlashMessage(exp.Message);
                return View();
            }
        } 

        //
        // POST: /Menu/Create

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(MenuViewEditModel m)
        {
            try
            {
                    UpdateModel(m);
                    var pid = Utils.ParseInt(Request["ddlParentMenu"]);
                    var leve1 = Utils.ParseInt(Request["ddlParentMenuLeve1"]);
                    pid = leve1 > 0 ? leve1 : pid;
                    var artCatID = Utils.ParseInt(Request["ArticleCategoryID"]);
                    var typeid = Utils.ParseInt(Request["ddlMenuType"]);
                    var chkPub = Request["chkPublic"] != null && Request["chkPublic"] != "false" ? true : false;
                    var pm = pid > 0 ? eDataContext.Menus.Where(e => e.ID == pid).SingleOrDefault() : null;
                    m.Menu.ParentID = pm != null ? pm.ID : (int?)null;
                    m.Menu.TypeID = pm != null ? pm.TypeID : typeid;
                    bool IsAutolink =bool.Parse(Request["AutoLink"]);
                    if (IsAutolink)
                    {
                        m.Menu.NavigateUrl = Settings.Default.MenuNavigateUrlDefault.ToString() + artCatID.ToString();
                    }
                    m.Menu.PubYN = chkPub;
                    m.Menu.ModifyBy = UserManager.GetUserId();
                    m.Menu.ModifyDate = DateTime.Now;
                    m.Menu.AddBy = UserManager.GetUserId();
                    m.Menu.AddDate = DateTime.Now;

                    eDataContext.Menus.InsertOnSubmit(m.Menu);
                    eDataContext.SubmitChanges();
                   
                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                //ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        
        
       //  GET: /Menu/Edit/5
        public ActionResult Edit(int id)
        {
            try
            {
                    MenuViewEditModel model = new MenuViewEditModel();
                    model.Menu = eDataContext.Menus.Where(e => e.ID == id).SingleOrDefault();
                    model.MenuTypes = eDataContext.MenuTypes.ToList();
                    model.ArticleCategories = eDataContext.ArticleCategories.Where(e => e.ActiveYN == true).ToList();
                    Regex rx = new Regex(@"(?<=index/)\d*");
                MatchCollection matches = rx.Matches(model.Menu.NavigateUrl);

                int number = 0;
                if (matches != null && matches.Count > 0)
                {
                 number = int.Parse(matches[0].Value.ToString());
                }

                ViewData["ArtCatID"] = number != null && number >0 ? number : 0;
                    return View(model);
            }
            catch (Exception exp)
            {
                Messages.AddFlashException(exp);
                return View();
            }
        }

        //
        // POST: /Menu/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, MenuViewEditModel m)
        {
            try
            {
                m.Menu = eDataContext.Menus.Where(e => e.ID == id).SingleOrDefault();
                UpdateModel(m);
                var pid = Utils.ParseInt(Request["ddlParentMenu"]);
                var leve1 = Utils.ParseInt(Request["ddlParentMenuLeve1"]);
                pid = leve1 > 0 ? leve1 : pid;
                var artCatID = Utils.ParseInt(Request["ArticleCategoryID"]);
                var typeid = Utils.ParseInt(Request["ddlMenuType"]);
                var chkPub = Request["chkPublic"] != null && Request["chkPublic"] != "false" ? true : false;
                var pm = pid > 0 ? eDataContext.Menus.Where(e => e.ID == pid).SingleOrDefault() : null;
                m.Menu.ParentID = pm != null ? pm.ID : (int?)null;
                m.Menu.TypeID = pm != null ? pm.TypeID : typeid;
                bool IsAutolink = bool.Parse(Request["AutoLink"]);
                if (IsAutolink)
                {
                    m.Menu.NavigateUrl = Settings.Default.MenuNavigateUrlDefault.ToString() + artCatID.ToString();
                }
                m.Menu.PubYN = chkPub;
                m.Menu.ModifyBy = UserManager.GetUserId();
                m.Menu.ModifyDate = DateTime.Now;
                eDataContext.SubmitChanges();

                return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                return View(m);
            }
        }

        //
        // GET: /Menu/Delete/5
        public ActionResult Delete(int id)
        {
            try
            {
                    var item = eDataContext.Menus.SingleOrDefault(e => e.ID == id);
                    return View(item);
            }
            catch (Exception exp)
            {
               
                return View();
            }
        }

        //
        // POST: /Menu/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                    var item = eDataContext.Menus.SingleOrDefault(e => e.ID == id);
                    if (item != null)
                    {
                        eDataContext.MenuMaps.DeleteAllOnSubmit(from m in eDataContext.MenuMaps where m.MenuTopID == id || m.LinkToID == id select m);
                        eDataContext.Menus.DeleteAllOnSubmit(from m in eDataContext.Menus where m.ParentID==id select m);
                        eDataContext.Menus.DeleteOnSubmit(item);
                        eDataContext.SubmitChanges();
                    }
                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                //ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
    }
}
